<template>
  <div class="custom-layout">
    <CustomNavbar />

    <div class="main-content">
      <div class="app-container">


        <!-- 数据卡片 -->
        <el-row :gutter="20" class="mb8">
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card" @click.native="getTodayRevenue">
              <div class="stat-content">
                <div class="stat-icon">
                  <i class="el-icon-money"></i>
                </div>
                <div class="stat-info">
                  <div class="stat-title">今日营收</div>
                  <div class="stat-value">{{totalAmount.toFixed(2)}}</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card" @click.native="refreshData">
              <div class="stat-content">
                <div class="stat-icon" style="background-color: #67C23A;">
                  <i class="el-icon-refresh"></i>
                </div>
                <div class="stat-info">
                  <div class="stat-title">最后刷新</div>
                  <div class="stat-value">{{lastRefreshTime}}</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card" @click.native="getRoomOccupancyRate">
              <div class="stat-content">
                <div class="stat-icon" style="background-color: #E6A23C;">
                  <i class="el-icon-office-building"></i>
                </div>
                <div class="stat-info">
                  <div class="stat-title">房间使用率</div>
                  <div class="stat-value">{{roomRate}}%</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card" @click.native="getNotProcessedOrders">
              <div class="stat-content">
                <div class="stat-icon" style="background-color: #F56C6C;">
                  <i class="el-icon-tickets"></i>
                </div>
                <div class="stat-info">
                  <div class="stat-title">待处理订单</div>
                  <div class="stat-value">{{noOrdersNum}}</div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 订单表格 -->
        <el-card shadow="never" class="table-card">
          <div slot="header" class="clearfix">
            <span>待处理订单</span>
            <el-button
              style="float: right; padding: 3px 0"
              type="text"
              icon="el-icon-refresh"
              @click="getNotProcessedOrders"
            >刷新</el-button>
          </div>

          <el-table
            v-loading="loading"
            :data="noOrdersList"
            @selection-change="handleSelectionChange"
            style="width: 100%"
          >
            <el-table-column label="名称" align="center" prop="name" />
            <el-table-column label="订单状态" align="center" prop="status" width="120">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                  {{ scope.row.status === 1 ? '已付款' : '未付款' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="处理状态" align="center" prop="payStatus" width="120">
              <template slot-scope="scope">
                <el-tag :type="scope.row.payStatus === 0 ? 'success' : 'warning'">
                  {{ scope.row.payStatus === 0 ? '已处理' : '待处理' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="付款时间" align="center" prop="payTime" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="120">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  @click="handleProcess(scope.row)"
                  :disabled="scope.row.payStatus === 0 || scope.row.status === 0"
                  :loading="scope.row.processing"
                >
                  处理
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getNotProcessedOrders"
          />
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import { getToalAccount, getRoomNum } from "@/api/home/home";
import {changeOrders, listOrders, updateOrders} from "@/api/orders/orders";
import CustomNavbar from '@/components/CustomNavbar';

export default {
  name: "Home",
  components: { CustomNavbar },
  data() {
    return {
      loading: false,
      showSearch: true,
      totalAmount: 0,
      roomRate: 0,
      noOrdersNum: 0,
      lastRefreshTime: '尚未刷新',
      noOrdersList: [],
      ids: [],
      dateRange: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        payStatus: 1 // 未处理订单
      }
    };
  },
  created() {
    this.refreshData();
  },
  methods: {
    // 刷新所有数据
    refreshData() {
      this.loading = true;
      Promise.all([
        this.getTodayRevenue(),
        this.getRoomOccupancyRate(),
        this.getNotProcessedOrders()
      ]).finally(() => {
        this.loading = false;
        this.lastRefreshTime = this.parseTime(new Date(), '{h}:{i}:{s}');
      });
    },

    // 日期范围变化
    handleDateChange(val) {
      if (val && val.length === 2) {
        this.queryParams.beginPayTime = val[0];
        this.queryParams.endPayTime = val[1];
      } else {
        this.queryParams.beginPayTime = null;
        this.queryParams.endPayTime = null;
      }
    },

    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.refreshData();
    },

    // 重置搜索
    resetQuery() {
      this.dateRange = [];
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        payStatus: 1
      };
      this.$refs.queryForm.resetFields();
      this.refreshData();
    },

    // 获取今日营收
    getTodayRevenue() {
      const params = {
        payTime: new Date().toLocaleDateString(),
        ...this.queryParams
      };
      return getToalAccount(params).then(response => {
        this.totalAmount = response || 0;
      });
    },

    // 获取房间使用率
    getRoomOccupancyRate() {
      const now = new Date();
      const beijingTimeStr = now.toLocaleString('zh-Cn', {
        timeZone: 'Asia/Shanghai',
        hour12: false
      }).replace(/\//g, '-').replace(/,/, '');

      return getRoomNum({
        currentTime: beijingTimeStr
      }).then(response => {
        this.roomRate = response || 0;
      });
    },

    // 获取未处理订单
    getNotProcessedOrders() {
      return listOrders(this.queryParams).then(response => {
        this.noOrdersList = response.rows || [];
        this.noOrdersNum = response.total || 0;
        this.total = response.total || 0;
      });
    },

    // 处理订单
    handleProcess(row) {
      this.$set(row, 'processing', true);
      const requestData = {
        id: row.id,
        payStatus: 0 // 0表示已处理
      };
      changeOrders(requestData)
        .then(() => {
          this.$modal.msgSuccess('订单处理成功');
          this.getNotProcessedOrders();
          this.getTodayRevenue();
        })
        .catch(() => {
          this.$modal.error('处理失败');
        })
        .finally(() => {
          this.$set(row, 'processing', false);
        });
    },

    // 选择变化
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
    },

    // 时间格式化
    parseTime(time, cFormat) {
      if (arguments.length === 0) {
        return null;
      }
      const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
      let date;
      if (typeof time === 'object') {
        date = time;
      } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
          time = parseInt(time);
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
          time = time * 1000;
        }
        date = new Date(time);
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      };
      const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key];
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value]; }
        return value.toString().padStart(2, '0');
      });
      return time_str;
    }
  }
};
</script>

<style>
/* 主内容区样式 */
.main-content {
  position: absolute;
  top: 0;
  left: 260px;
  width: calc(100% - 260px);
  height: 100vh;
  overflow-y: auto;
  background: #f5f7fa;
  z-index: 10;
  padding: 20px;
}

.app-container {
  background: white;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

/* 数据卡片样式 */
.stat-card {
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 20px;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  background: linear-gradient(135deg, #8B5FBF, #61398F);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
  margin-right: 15px;
}

.stat-info {
  flex: 1;
}

.stat-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

/* 表格卡片样式 */
.table-card {
  margin-top: 20px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .el-col {
    width: 50%;
  }
}

@media (max-width: 768px) {
  .main-content {
    left: 0;
    width: 100%;
  }

  .el-col {
    width: 100%;
  }

  .stat-content {
    flex-direction: column;
    text-align: center;
  }

  .stat-icon {
    margin-right: 0;
    margin-bottom: 10px;
  }
}
</style>
